/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package gui;

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileNameExtensionFilter;
import modelo.GestorHistoriaClinica;
import pojos.Paciente;

/**
 * Panel de Consulta de Historias Clinicas segun un paciente introducido por el usuario
 * @author Ⓒvenegas
 */
public class PanelHistoriaClinica extends javax.swing.JPanel {

    private final VentanaPrincipal ventana;
    private final GestorHistoriaClinica gestor;
    private Paciente paciente;
    private boolean pacienteTieneHistoriaClinica;
    
    /**
     * Creates new form jPanelHistoriaClinica
     */
    PanelHistoriaClinica(VentanaPrincipal ventana) {
        this.ventana = ventana;
        initComponents();
        this.gestor = new GestorHistoriaClinica(this);
        this.pacienteTieneHistoriaClinica = false;
        //Añadimos el listener al texfield para poder buscar pulsando enter
        //además de "clickar" en el boton Buscar
        this.addKeyListener();
        this.setFocusable(true);
        this.requestFocus();
    }
    
    
    /**
     * Añadimos el listener al texfield para poder buscar pulsando enter
     * además de "clickar" en el boton Buscar
     */
    private void addKeyListener(){
        this.jTextFieldHC_dni_cod.addKeyListener(new KeyAdapter(){
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_ENTER){
                    buscar();
                }
            }
        });
    }
    
    
    /**
     * Busca un paciente por Codigo o DNI (segun eleccion del comboBox)
     */
    private void buscar(){
        
        gestor.clearList();
        pacienteTieneHistoriaClinica = false;
        
        Integer codPaciente = null;
        String dni;
        
        if (jTextFieldHC_dni_cod.getText()==null){
            JOptionPane.showMessageDialog(this.getParent(),
            "Introduce DNI/CodPaciente", "Hospital", JOptionPane.INFORMATION_MESSAGE);
        }else{
            
            switch (jComboBoxHC_tipoID.getSelectedIndex()){
                
                case 0:
                    try{
                        codPaciente = Integer.parseInt(jTextFieldHC_dni_cod.getText());
                        
                        paciente = gestor.buscarPaciente(codPaciente);
                        
                        if (paciente == null){
                            mostrarDialogo("No exite un Paciente con el siguiente COD: " + codPaciente);
                        }else{
                            if (JOptionPane.showConfirmDialog(this, "Datos del Paciente:\n\n" + paciente + "\n\n ¿Desea consultar su historia clínica?") == JOptionPane.OK_OPTION){
                                pacienteTieneHistoriaClinica = gestor.setlistaProcAsistenciales(paciente);
                                
                                if (pacienteTieneHistoriaClinica == false){
                                    mostrarDialogo(paciente.getNombre() + " " + paciente.getApellido1() + " no tiene ningún proceso asistencial asociado");
                                }
                            }
                        }
                        
                    }catch (NumberFormatException nfEx){
                        mostrarDialogo("Introduce Codigo de paciente valido (Solo numeros)\n\nEjemplo: 1234");
                    }
                    break;
                case 1:
                    dni = jTextFieldHC_dni_cod.getText();
                    if (dni.length() == 9){
                        
                        paciente = gestor.buscarPaciente(dni);
                        
                        if (paciente == null){
                            mostrarDialogo("No exite un Paciente con el siguiente DNI: " + dni);
                        }else{
                            if (JOptionPane.showConfirmDialog(this, "Datos del Paciente:\n\n" + paciente + "\n\n ¿Desea consultar su historia clínica?") == JOptionPane.OK_OPTION){
                                
                                pacienteTieneHistoriaClinica = gestor.setlistaProcAsistenciales(paciente);
                                
                                if (pacienteTieneHistoriaClinica == false){
                                    mostrarDialogo(paciente.getNombre() + " " + paciente.getApellido1() + " no tiene ningún proceso asistencial asociado");
                                }
                            }
                        }
                        
                        
                    }else{
                        mostrarDialogo("Introduce DNI valido (8 nums y 1 letra)\n\nEjemplo: 12345678B");
                    }
                    break;
                    
                    
                default:
                    break;
            }
        }
        
    }
    
    
    
    private void exportarExcel(){
        boolean seHaExportadoConExito;
         
        if (paciente == null){
            mostrarDialogo("Busca primero un paciente");
        }else{
            
            if (pacienteTieneHistoriaClinica == true){
                File file = null;
                JFileChooser fcImportar = new JFileChooser(new File (".").getAbsolutePath ());
                FileNameExtensionFilter filtroExtension = new FileNameExtensionFilter("Excell File (*.xls)", "xls","XLS");
                fcImportar.setFileFilter(filtroExtension);
                //int accion = fcImportar.showOpenDialog(fcImportar);
                int accion = fcImportar.showSaveDialog(fcImportar/* o poner si no 'this' */);
                String path = "";

                if (accion == JFileChooser.APPROVE_OPTION) {
                    file = fcImportar.getSelectedFile();
                    path = file.getAbsolutePath();
                    if(!path.endsWith(".xls")){
                        path += ".xls";
                    }
                    
                    
                    seHaExportadoConExito = gestor.exportarExcel(path);
                    
                    if (seHaExportadoConExito){
                        mostrarDialogo("Historia Clinica Exportada con Éxito");
                    }else{
                        mostrarDialogo("No se ha podido exportar la Historia Clinica\n\nPor favor, inténtelo de nuevo o póngase en \ncontacto con el Administrador\n\ncristina.castellanos@juanxxiii.net");
                    }
                    
                }
            }else{
                mostrarDialogo("El paciente " + paciente.getNombre() + " " + paciente.getApellido1() + "No tiene hostORIA Clinica");
            }
            
            
        }
    }
    
    
    /**
     * Muestra un dialogo en el JPanel
     * @param msg texto del mensaje del JOptionPane
     */
    private void mostrarDialogo(String msg) {
        JOptionPane.showMessageDialog(this.getParent(),
            msg, "Hosptital - Historia Clinica", JOptionPane.INFORMATION_MESSAGE);
    }
    

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jTabbedPane = new javax.swing.JTabbedPane();
        panelInt = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTableHC_Intervenciones = new javax.swing.JTable();
        panelIng = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTableHC_Ingresos = new javax.swing.JTable();
        panelCon = new javax.swing.JPanel();
        jScrollPane3 = new javax.swing.JScrollPane();
        jTableHC_Consultas = new javax.swing.JTable();
        panelUrg = new javax.swing.JPanel();
        jScrollPane4 = new javax.swing.JScrollPane();
        jTableHC_Urgencias = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        jTextFieldHC_dni_cod = new javax.swing.JTextField();
        jButtonHC_Exportar = new javax.swing.JButton();
        jComboBoxHC_tipoID = new javax.swing.JComboBox();
        jButtonHC_Buscar = new javax.swing.JButton();

        jTableHC_Intervenciones.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "ID", "Fecha", "Nº Quirófano", "Especialidad"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, true, false, true
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(jTableHC_Intervenciones);

        javax.swing.GroupLayout panelIntLayout = new javax.swing.GroupLayout(panelInt);
        panelInt.setLayout(panelIntLayout);
        panelIntLayout.setHorizontalGroup(
            panelIntLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelIntLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 755, Short.MAX_VALUE)
                .addContainerGap())
        );
        panelIntLayout.setVerticalGroup(
            panelIntLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelIntLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 353, Short.MAX_VALUE)
                .addContainerGap())
        );

        jTabbedPane.addTab("INTERVENCIONES", panelInt);

        jTableHC_Ingresos.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null},
                {null, null, null},
                {null, null, null},
                {null, null, null},
                {null, null, null},
                {null, null, null},
                {null, null, null},
                {null, null, null},
                {null, null, null},
                {null, null, null}
            },
            new String [] {
                "ID", "Fecha Ingreso", "Fecha Alta"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.Object.class, java.lang.Object.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane2.setViewportView(jTableHC_Ingresos);

        javax.swing.GroupLayout panelIngLayout = new javax.swing.GroupLayout(panelIng);
        panelIng.setLayout(panelIngLayout);
        panelIngLayout.setHorizontalGroup(
            panelIngLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelIngLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 755, Short.MAX_VALUE)
                .addContainerGap())
        );
        panelIngLayout.setVerticalGroup(
            panelIngLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelIngLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 353, Short.MAX_VALUE)
                .addContainerGap())
        );

        jTabbedPane.addTab("INGRESOS", panelIng);

        jTableHC_Consultas.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null}
            },
            new String [] {
                "ID", "Fecha", "Hora Entrada", "Hora Salida", "Especialidad"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane3.setViewportView(jTableHC_Consultas);

        javax.swing.GroupLayout panelConLayout = new javax.swing.GroupLayout(panelCon);
        panelCon.setLayout(panelConLayout);
        panelConLayout.setHorizontalGroup(
            panelConLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelConLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 755, Short.MAX_VALUE)
                .addContainerGap())
        );
        panelConLayout.setVerticalGroup(
            panelConLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelConLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 353, Short.MAX_VALUE)
                .addContainerGap())
        );

        jTabbedPane.addTab("CONSULTAS", panelCon);

        jTableHC_Urgencias.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null},
                {null, null, null},
                {null, null, null},
                {null, null, null},
                {null, null, null},
                {null, null, null},
                {null, null, null},
                {null, null, null},
                {null, null, null},
                {null, null, null}
            },
            new String [] {
                "ID", "Fecha Urgencia", "Fecha Alta"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.Object.class, java.lang.Object.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane4.setViewportView(jTableHC_Urgencias);

        javax.swing.GroupLayout panelUrgLayout = new javax.swing.GroupLayout(panelUrg);
        panelUrg.setLayout(panelUrgLayout);
        panelUrgLayout.setHorizontalGroup(
            panelUrgLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelUrgLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane4, javax.swing.GroupLayout.DEFAULT_SIZE, 755, Short.MAX_VALUE)
                .addContainerGap())
        );
        panelUrgLayout.setVerticalGroup(
            panelUrgLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelUrgLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane4, javax.swing.GroupLayout.DEFAULT_SIZE, 353, Short.MAX_VALUE)
                .addContainerGap())
        );

        jTabbedPane.addTab("URGENCIAS", panelUrg);

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setText("HISTORIA CLINICA");

        jButtonHC_Exportar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconos/ico_excel.png"))); // NOI18N
        jButtonHC_Exportar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonHC_ExportarActionPerformed(evt);
            }
        });

        jComboBoxHC_tipoID.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Cod Paciente", "DNI / NIE" }));
        jComboBoxHC_tipoID.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBoxHC_tipoIDActionPerformed(evt);
            }
        });

        jButtonHC_Buscar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconos/ico_find.png"))); // NOI18N
        jButtonHC_Buscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonHC_BuscarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jTabbedPane)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jComboBoxHC_tipoID, javax.swing.GroupLayout.PREFERRED_SIZE, 153, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jTextFieldHC_dni_cod, javax.swing.GroupLayout.PREFERRED_SIZE, 169, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jButtonHC_Buscar, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(22, 22, 22)
                        .addComponent(jButtonHC_Exportar, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 52, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(26, 26, 26)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jTextFieldHC_dni_cod, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jComboBoxHC_tipoID, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jButtonHC_Exportar, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButtonHC_Buscar, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jTabbedPane, javax.swing.GroupLayout.PREFERRED_SIZE, 400, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(73, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void jButtonHC_ExportarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonHC_ExportarActionPerformed
        // TODO add your handling code here:
        
        exportarExcel();
        
    }//GEN-LAST:event_jButtonHC_ExportarActionPerformed

    private void jComboBoxHC_tipoIDActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBoxHC_tipoIDActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jComboBoxHC_tipoIDActionPerformed

    private void jButtonHC_BuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonHC_BuscarActionPerformed
        // TODO add your handling code here:
         buscar();
    }//GEN-LAST:event_jButtonHC_BuscarActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonHC_Buscar;
    private javax.swing.JButton jButtonHC_Exportar;
    private javax.swing.JComboBox jComboBoxHC_tipoID;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;
    public javax.swing.JTabbedPane jTabbedPane;
    public javax.swing.JTable jTableHC_Consultas;
    public javax.swing.JTable jTableHC_Ingresos;
    public javax.swing.JTable jTableHC_Intervenciones;
    public javax.swing.JTable jTableHC_Urgencias;
    private javax.swing.JTextField jTextFieldHC_dni_cod;
    public javax.swing.JPanel panelCon;
    public javax.swing.JPanel panelIng;
    public javax.swing.JPanel panelInt;
    public javax.swing.JPanel panelUrg;
    // End of variables declaration//GEN-END:variables
}
